<template>
	<div class="signature-pad">
		<!-- 签名画布区域 -->
		<div class="signature-container">
			<canvas
				ref="canvas"
				class="signature-canvas"
				@mousedown="startDrawing"
				@mousemove="draw"
				@mouseup="stopDrawing"
				@mouseleave="stopDrawing"
				@touchstart="handleTouchStart"
				@touchmove="handleTouchMove"
				@touchend="handleTouchEnd"
			></canvas>
			<div class="signature-hint" v-if="!hasSignature">
				请在上方区域使用鼠标签名
			</div>
		</div>

		<!-- 操作按钮 -->
		<div class="signature-controls">
			<button class="control-btn clear-btn" @click="clearCanvas">
				<i class="icon-clear"></i> 清除
			</button>
			<button
				class="control-btn save-btn"
				@click="saveSignature"
				:disabled="!hasSignature"
			>
				<i class="icon-save"></i> 保存签名
			</button>
		</div>

		<!-- 签名预览和base64信息 -->
		<div class="signature-preview" v-if="signatureImage">
			<h4>签名预览：</h4>
			<img :src="signatureImage" alt="签名图片" class="preview-image" />

			<div class="base64-section">
				<div class="base64-header">
					<span>Base64 格式：</span>
					<button class="copy-btn" @click="copyBase64">
						<i class="icon-copy"></i> 复制
					</button>
				</div>
				<textarea
					class="base64-textarea"
					:value="signatureImage"
					readonly
					rows="4"
					placeholder="签名的base64编码将显示在这里"
				></textarea>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'SignaturePad',
	data() {
		return {
			canvas: null, // canvas元素
			ctx: null, // canvas 2D上下文
			isDrawing: false, // 是否正在绘制
			lastX: 0, // 上一个X坐标
			lastY: 0, // 上一个Y坐标
			signatureImage: '', // 签名图片的base64
			hasSignature: false, // 是否有签名内容

			// 画笔配置
			strokeColor: '#000000', // 画笔颜色
			lineWidth: 2, // 线条宽度
		}
	},
	mounted() {
		// 初始化画布
		this.initCanvas()
	},
	methods: {
		/**
		 * 初始化画布
		 */
		initCanvas() {
			this.canvas = this.$refs.canvas
			this.ctx = this.canvas.getContext('2d')

			// 设置画布尺寸
			this.resizeCanvas()

			// 监听窗口大小变化，调整画布尺寸
			window.addEventListener('resize', this.resizeCanvas)

			// 初始化画笔样式
			this.ctx.strokeStyle = this.strokeColor
			this.ctx.lineWidth = this.lineWidth
			this.ctx.lineJoin = 'round' // 线条连接样式
			this.ctx.lineCap = 'round' // 线条端点样式
		},

		/**
		 * 调整画布尺寸以适应容器
		 */
		resizeCanvas() {
			const container = this.canvas.parentElement
			if (container) {
				// 设置画布的实际尺寸（避免绘制模糊）
				this.canvas.width = container.clientWidth
				this.canvas.height = 300

				// 设置画布的CSS尺寸
				this.canvas.style.width = '100%'
				this.canvas.style.height = '300px'
			}
		},

		/**
		 * 开始绘制（鼠标按下）
		 */
		startDrawing(e) {
			this.isDrawing = true

			// 获取鼠标在画布上的位置
			const { offsetX, offsetY } = this.getPosition(e)
			this.lastX = offsetX
			this.lastY = offsetY
		},

		/**
		 * 绘制中（鼠标移动）
		 */
		draw(e) {
			if (!this.isDrawing) return

			const { offsetX, offsetY } = this.getPosition(e)

			// 开始绘制路径
			this.ctx.beginPath()
			// 从上次的位置开始
			this.ctx.moveTo(this.lastX, this.lastY)
			// 绘制到当前位置
			this.ctx.lineTo(offsetX, offsetY)
			// 描边路径
			this.ctx.stroke()

			// 更新上次位置
			this.lastX = offsetX
			this.lastY = offsetY

			// 标记已有签名
			this.hasSignature = true
		},

		/**
		 * 停止绘制（鼠标释放或离开）
		 */
		stopDrawing() {
			this.isDrawing = false
		},

		/**
		 * 处理触摸开始（移动端）
		 */
		handleTouchStart(e) {
			e.preventDefault() // 防止触摸事件被浏览器默认处理
			const touch = e.touches[0]
			this.startDrawing({
				clientX: touch.clientX,
				clientY: touch.clientY,
			})
		},

		/**
		 * 处理触摸移动（移动端）
		 */
		handleTouchMove(e) {
			e.preventDefault()
			if (!this.isDrawing) return
			const touch = e.touches[0]
			this.draw({
				clientX: touch.clientX,
				clientY: touch.clientY,
			})
		},

		/**
		 * 处理触摸结束（移动端）
		 */
		handleTouchEnd() {
			this.stopDrawing()
		},

		/**
		 * 获取鼠标/触摸在画布上的位置
		 */
		getPosition(e) {
			const rect = this.canvas.getBoundingClientRect()
			return {
				offsetX: e.clientX - rect.left,
				offsetY: e.clientY - rect.top,
			}
		},

		/**
		 * 清除画布内容
		 */
		clearCanvas() {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
			this.signatureImage = ''
			this.hasSignature = false
		},

		/**
		 * 保存签名为base64图片
		 */
		saveSignature() {
			// 将画布内容转换为base64格式的图片
			// 可选格式: 'image/png' (默认), 'image/jpeg' 等
			this.signatureImage = this.canvas.toDataURL('image/png')

			// 触发事件，将base64图片传递给父组件
			this.$emit('signature-saved', this.signatureImage)
		},

		/**
		 * 复制base64到剪贴板
		 */
		copyBase64() {
			navigator.clipboard
				.writeText(this.signatureImage)
				.then(() => {
					alert('Base64已复制到剪贴板')
				})
				.catch((err) => {
					console.error('复制失败:', err)
					alert('复制失败，请手动复制')
				})
		},
	},
	beforeDestroy() {
		// 移除事件监听，防止内存泄漏
		window.removeEventListener('resize', this.resizeCanvas)
	},
}
</script>

<style scoped>
.signature-pad {
	max-width: 800px;
	margin: 0 auto;
	padding: 20px;
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
		sans-serif;
}

.signature-container {
	border: 2px dashed #ccc;
	border-radius: 8px;
	margin-bottom: 20px;
	position: relative;
	background-color: #fff;
}

.signature-canvas {
	cursor: crosshair;
	width: 100%;
	height: 300px;
}

.signature-hint {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	color: #999;
	font-size: 14px;
	pointer-events: none;
}

.signature-controls {
	display: flex;
	gap: 15px;
	margin-bottom: 30px;
	justify-content: center;
}

.control-btn {
	padding: 10px 24px;
	border: none;
	border-radius: 6px;
	cursor: pointer;
	font-size: 15px;
	font-weight: 500;
	display: inline-flex;
	align-items: center;
	gap: 8px;
	transition: all 0.2s ease;
}

.clear-btn {
	background-color: #f5f5f5;
	color: #333;
	border: 1px solid #e0e0e0;
}

.clear-btn:hover {
	background-color: #e9e9e9;
}

.save-btn {
	background-color: #42b983;
	color: white;
}

.save-btn:disabled {
	background-color: #a5d6b9;
	cursor: not-allowed;
}

.save-btn:not(:disabled):hover {
	background-color: #359e6d;
}

.signature-preview {
	margin-top: 20px;
	padding: 20px;
	border-radius: 8px;
	background-color: #f9f9f9;
	animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.signature-preview h4 {
	margin-top: 0;
	color: #333;
	font-size: 16px;
}

.preview-image {
	max-width: 100%;
	border: 1px solid #eee;
	border-radius: 4px;
	margin-bottom: 15px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.base64-section {
	margin-top: 15px;
}

.base64-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8px;
}

.base64-header span {
	color: #666;
	font-size: 14px;
}

.copy-btn {
	padding: 6px 12px;
	background-color: #2196f3;
	color: white;
	border: none;
	border-radius: 4px;
	cursor: pointer;
	font-size: 13px;
	display: inline-flex;
	align-items: center;
	gap: 5px;
}

.copy-btn:hover {
	background-color: #0b7dda;
}

.base64-textarea {
	width: 100%;
	box-sizing: border-box;
	border: 1px solid #ddd;
	border-radius: 6px;
	padding: 12px;
	font-family: monospace;
	font-size: 12px;
	resize: vertical;
	background-color: #fff;
}

/* 图标样式 */
.icon-clear,
.icon-save,
.icon-copy {
	width: 16px;
	height: 16px;
	display: inline-block;
}

.icon-clear {
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23333' d='M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'/%3E%3C/svg%3E");
}

.icon-save {
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z'/%3E%3C/svg%3E");
}

.icon-copy {
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z'/%3E%3C/svg%3E");
}
</style>
